<template>
    <div class="w-100 head d-flex justify-content-center align-items-center top-nav-list">
        <div class="flex-grow-1">
            <div class="headLogo d-flex justify-content-center align-items-center">
                <img class="logo rounded" :src="$store.state.logoUrl" alt="LOGO">
            </div>
        </div>
        <!--<div class="mx-5">-->
            <!--<el-dropdown>-->
                <!--<span class="el-dropdown-link d-inline-block d-flex align-items-center fontColor" style="height: 65px;cursor: pointer">-->
                    <!--<i class="fa fa-rmb icon"></i> 账户余额 : {{userInfo.cost}}元-->
                <!--</span>-->
            <!--</el-dropdown>-->
        <!--</div>-->
        <div class="mr-5">
            <el-dropdown @command="handleCommand">
            <span class="el-dropdown-link d-inline-block d-flex align-items-center fontColor"
                  style="height: 65px;cursor: pointer">
            <i class="fa fa-address-book-o icon"></i>{{userInfo.name}}({{userInfo.phone}})
            </span>
                <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="changePassword">密码修改</el-dropdown-item>
                    <el-dropdown-item command="changeNickName">昵称修改</el-dropdown-item>
                    <el-dropdown-item command="loginOut">退出</el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown>
        </div>
        <el-dialog
                title="用户信息"
                :visible.sync="settingDialog"
                :close-on-click-modal="false"
                width="500px"
                center>
            <div>
                <el-form label-width="80px" status-icon :model="user" :rules="rules" ref="user">
                    <el-form-item label="昵称" prop="name" v-if="isNickName == '1'">
                        <el-input v-model="user.name" placeholder="请输入昵称" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="旧密码" prop="oldPassword" v-if="isNickName == '2'">
                        <el-input v-model="user.oldPassword" placeholder="请输入旧密码" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="新密码" prop="newPassword" v-if="isNickName == '2'">
                        <el-input v-model="user.newPassword" placeholder="请输入新密码" autocomplete="off"></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
        <el-button @click="settingDialog = false">取 消</el-button>
        <el-button type="primary" :loading="loading" :disabled="loading" @click="submitForm('user')">{{loading?'修改中':'确定修改'}}</el-button>
      </span>
        </el-dialog>
    </div>
</template>

<script>
    import {mapGetters,mapActions} from 'vuex';
    export default {
        name: 'topNav',
        data() {
            var validatePassOld = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入旧密码'));
                } else {
                    var r = /^[^\u4e00-\u9fa5]+$/
                    if (!r.test(value)) {
                        callback(new Error('密码不能为中文!'));
                    }
                    if (value.length < 6) {
                        callback(new Error('密码长度在 6 到 18 个字符!'));
                    }
                    callback();
                }
            };
            var validatePassNew = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入新密码'));
                } else {
                    var r = /^[^\u4e00-\u9fa5]+$/
                    if (!r.test(value)) {
                        callback(new Error('密码不能为中文!'));
                    }
                    if (value.length < 6) {
                        callback(new Error('密码长度在 6 到 18 个字符!'));
                    }

                    callback();
                }
            };
            return {
                url:'',
                rules: {
                    name: [
                        {required: true, message: '请输入昵称', trigger: 'change'}
                    ],
                    oldPassword: [
                        {validator: validatePassOld, trigger: 'change'}
                    ],
                    newPassword: [
                        {validator: validatePassNew, trigger: 'change'}
                    ]
                },
                isNickName: '',
                settingDialog: false,
                loading: false,
                user: {
                    name: '',
                    oldPassword: '',
                    newPassword: ''
                },
                userInfo: {}
            }
        },
        watch: {
            getLogoUrl: function(url) {
                console.log("改变", url)
            },
            settingDialog: function (val) {
                if (!val) {
                    this.user.oldPassword = '';
                    this.user.newPassword = '';
                    this.user.name = '';
                    this.$refs['user'].resetFields();
                }
            }
        },
        computed:{
            ...mapGetters([
                'getLogoUrl'
            ])
        },
        created() {
            if (!localStorage.getItem('logoUrl')) {
                this.getLogo();
            } else {
                var link = document.querySelector("link[rel*='icon']") || document.createElement('link');
                link.type = 'image/x-icon';
                link.rel = 'shortcut icon';
                link.href =localStorage.getItem('logoUrl');
                document.getElementsByTagName('head')[0].appendChild(link);
                this.$store.commit('setLogoUrl',localStorage.getItem('logoUrl'))
            }
            this.userInfo = JSON.parse(localStorage.getItem('userInfo'));
        },
        methods: {
            getLogo(){
                this.$http.get('api/admin/system/setting')
                    .then((res) => {
                        if (res.data && res.data.length > 0) {
                            this.$store.commit('setLogoUrl',res.data[0].pic_url)
                            var link = document.querySelector("link[rel*='icon']") || document.createElement('link');
                            link.type = 'image/x-icon';
                            link.rel = 'shortcut icon';
                             link.href = res.data[0].pic_url;
                            document.getElementsByTagName('head')[0].appendChild(link);
                        }
                    })
                    .catch((err) => {
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            handleCommand(command) {
                if (command == 'changeNickName') {
                    this.settingDialog = true;
                    this.isNickName = '1';
                } else if (command == 'changePassword') {
                    this.settingDialog = true;
                    this.isNickName = '2';
                } else if (command == 'loginOut') {
                    localStorage.clear();
                    this.$router.push({name: 'login'})
                }
            },
            submitForm(formName) {
                let _this = this;
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        if (this.isNickName == '1') {
                            _this.setNickName();
                        } else if (this.isNickName == '2') {
                            _this.setPassWord();
                        }

                    } else {
                        return false;
                    }
                });
            },
            setNickName() {
                this.loading = true;
                this.$http.put('api/admin/common/user/' + this.userInfo.id + '?name=' + this.user.name)
                    .then((res) => {
                        this.$message.success('昵称修改成功！');
                        localStorage.setItem('userInfo', JSON.stringify(res.data));
                        this.userInfo.name = this.user.name;
                        this.settingDialog = false;
                        this.loading = false;
                    })
                    .catch((err) => {
                        this.loading = false;
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            setPassWord() {
                this.loading = true;
                this.$http.put('api/admin/user/session/password?oldpwd=' + this.user.oldPassword + '&newpwd=' + this.user.newPassword)
                    .then((res) => {
                        this.$message.success('密码修改成功！');
                        this.settingDialog = false;
                        this.user.oldPassword = '';
                        this.user.newPassword = '';
                        this.loading = false;
                    })
                    .catch((err) => {
                        this.loading = false;
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            }
        }
    };
</script>
<style lang="less">
    .top-nav-list {

    }

</style>
<style scoped>
    .head {
        width: 100vw;
        background-color: #374254;
        color: #bfcbd9;
    }

    .headLogo {
        width: 200px;
        height: 65px;
    }

    .logo {
        /*width: 50px;*/
        max-height: 40px;
    }
</style>